<?php

namespace zzcms\primary\controller;


use think\Db;

class Help extends Base
{
    // 初始化
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 关键词搜索
     * url:http://www.xmyeditor.com/apimobile/help/search.html
     * 必传参数: keyword：关键词
     * 选传参数:无
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    keyword：关键词  hot_keywords：热门搜索   keywords：下拉关键词  lists：搜索结果列表
     *
     */
    public function search()
    {
        $keyword = isset($this->info['keyword']) ? $this->info['keyword'] : '';
        if (empty($keyword)) {
            $this->array2json(['code' => 1, 'msg' => '缺少参数']);
        }

        $p = isset($this->info['p']) ? max(intval($this->info['p']), 1) : 1;
        //解析传过来的参数值
        $keyword = urldecode($keyword);
        $keyword = str_replace('.', '', $keyword);
        $keyword = str_replace('、', '', $keyword);
        //引入迅搜,搜索入热词需要用到
        include EXTEND_PATH . 'xunsearch/lib/XS.php';
        $xs = new \XS('article');
        $search = $xs->search;
        //分类缓存
        $category_cache = getCache('article_category');
        //排序顺序，标题权重-内容权重（帮助中心-TOP问答-通知公告）
        $help_title_lists = $help_content_lists = $top_title_lists = $top_content_lists = $notice_title_lists = $notice_content_lists = [];
        //当搜索为数字时，用SQL查询即可
        if (is_numeric($keyword)) {
            $article_model = new \zzcms\home\model\Article();
            //$lists = $article_model->getList(['where' => ['id' => $keyword]]);
            $lists = $article_model->where(['id' => $keyword])->whereOr(['errorcode' => $keyword])->select();
            foreach ($lists as $k => $item) {
                $cateinfo = isset($category_cache[$item['cateid']]) ? $category_cache[$item['cateid']] : [];
                $data = [
                    'id' => $item['id'],
                    'module' => 1,
                    'title' => htmlspecialchars_decode($item['title']),
                    'content' => strip_tags(htmlspecialchars_decode($item['content'])),
                    'catename' => $cateinfo ? $cateinfo['catename'] : '',
                    'type' => $cateinfo ? $cateinfo['module'] : '',
                    'hits' => $item['hits'],
                    'url' => $item['url'],
                ];
                //通知公告的内容要排在最后
                if ($item['cateid'] == 1) {
                    $notice_title_lists[] = $data;
                } else {
                    $help_title_lists[] = $data;
                }
            }
            $answer_model = new \zzcms\home\model\ArticleAnswer();
            $lists = $answer_model->getList(['where' => ['id' => $keyword]]);
            foreach ($lists as $k => $item) {
                $cateinfo = isset($category_cache[$item['cateid']]) ? $category_cache[$item['cateid']] : [];
                $data = [
                    'id' => $item['id'],
                    'module' => 2,
                    'title' => htmlspecialchars_decode($item['question']),
                    'content' => strip_tags(htmlspecialchars_decode($item['result'])),
                    'catename' => $cateinfo ? $cateinfo['catename'] : '',
                    'type' => 'answer',
                    'hits' => 0,
                    'url' => '',
                ];
                $top_title_lists[] = $data;
            }
            //按权重顺序合并数组
            $lists = array_merge($help_title_lists, $top_title_lists, $notice_title_lists);
        } else {
            $homoionyms = getCache('homoionym');
            //搜索关键词长度
            $keyword_lenth = mb_strlen($keyword, "UTF8");

            //判断是否需要分词
            $words_array = [$keyword];
            if ($keyword_lenth > 2) {
                $words_array = array_merge($words_array, explode(',', $this->getTags($keyword)));

            }
            //cateid 9:全部  1：图库 2：素材库 3：全文模板 4：帮助中心
            foreach ($homoionyms as $k => $item) {
                $homoionyms_array = explode(' ', $item['words']);
                if (in_array($item['cateid'], [4, 9]) && in_array($keyword, $homoionyms_array)) {
                    $words_array = array_merge($words_array, $homoionyms_array);
                }
            }
            //去除重新的关键词
            $words_array = array_unique($words_array);
            if (count($words_array) > 8) {
                $words_array = array_slice($words_array, 0, 8);
            }

            $keyword_str = implode(' OR ', $words_array);
            if (strlen($keyword_str) > 180) {
                $keyword_array = explode(' OR ', substr($keyword_str, 0, 180));
                array_pop($keyword_array);
                $keyword_str = implode(' OR ', $keyword_array);
            }
            // 获取搜索结果的匹配总数估算值
            $pagesize = 300;
            $limit = max(($p - 1) * $pagesize, 0);
            $artilces = $search->addDb('answer')->addWeight('title', $keyword)->setQuery($keyword_str)->setLimit($pagesize, $limit)->search();


            //ID集合
            $article_ids = $answer_ids = [];
            //(new \zzcms\home\model\ArticleCategory())->getCache();

            foreach ($artilces as $k => $item) {
                $cateinfo = isset($category_cache[$item['cateid']]) ? $category_cache[$item['cateid']] : [];
                $data = [
                    'id' => substr($item['id'], 1),
                    'module' => $item['module'],
                    'title' => $search->highlight($item['title']),
                    'content' => $search->highlight(strip_tags($item['content'])),
                    'catename' => $cateinfo ? $cateinfo['catename'] : '',
                    'type' => $cateinfo ? $cateinfo['module'] : 'answer',
                ];
                if ($item['module'] == 1) {
                    $article_ids[] = $data['id'];
                    //标题中是否包含关键词
                    if (strpos($data['title'], $keyword)) {
                        //通知公告的内容要排在最后
                        if ($item['cateid'] == 1) {
                            $notice_title_lists[] = $data;
                        } else {
                            $help_title_lists[] = $data;
                        }
                    } else {
                        //通知公告的内容要排在最后
                        if ($item['cateid'] == 1) {
                            $notice_content_lists[] = $data;
                        } else {
                            $help_content_lists[] = $data;
                        }
                    }
                } else {
                    $answer_ids[] = $data['id'];
                    //标题中是否包含关键词
                    if (strpos($data['title'], $keyword)) {
                        $top_title_lists[] = $data;
                    } else {
                        $top_content_lists[] = $data;
                    }
                }
            }
            //按权重顺序合并数组
            $lists = array_merge($help_title_lists, $top_title_lists, $notice_title_lists, $help_content_lists, $top_content_lists, $notice_content_lists);
            //查询文章阅读数
            $article_model = new \zzcms\home\model\Article();
            $article_lists = $article_model->field('id,hits,url')->where(['id' => ['in', $article_ids]])->select();

            $article_array = [];
            foreach ($article_lists as $item) {
                $article_array[$item['id']] = $item->toArray();
            }
            //文章的点击量数量
            foreach ($lists as $k => $item) {
                if ($item['module'] == 1) {
                    $item['hits'] = isset($article_array[$item['id']]) ? $article_array[$item['id']]['hits'] : 0;
                    $item['url'] = isset($article_array[$item['id']]) ? $article_array[$item['id']]['url'] : '';
                } else {
                    $item['hits'] = 0;
                    $item['url'] = '';
                }
                $lists[$k] = $item;
            }

        }


        //关键字
        $keyword_list = $search->getHotQuery();
        $hot_keywords = [];
        foreach ($keyword_list as $key => $item) {
            $hot_keywords[] = ['keyword' => $key];
        }

        $data = [
            'keyword' => $keyword,
            'hot_keywords' => $hot_keywords,
            'keywords' => getCache('down_keyword'),
            'lists' => $lists,
        ];
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }


    /**
     * 文档内容
     * url:http://www.xmyeditor.com/apimobile/help/detail.html
     * 必传参数: id：文档ID
     * 选传参数:无
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    info：信息内容
     *
     */
    public function detail()
    {
        $id = isset($this->info['id']) ? intval($this->info['id']) : 0;
        if ($id < 1) {
            $this->array2json(['code' => 1, 'msg' => '缺少参数']);
        }
        $model = new \zzcms\home\model\Article();
        $info = $model->getOne($id);
        if (empty($info)) {
            $id = 55;
            $info = $model->getOne($id);
        }
        //计数+1
        $model->where(['id' => $id])->setInc('hits');
        $info['content'] = htmlspecialchars_decode($info['content']);
        $data = [
            'info' => $info
        ];
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }


    /**
     * 分类列表带下属文档标题
     * url:http://www.xmyeditor.com/apimobile/help/categoryArticle.html
     * 必传参数: 无
     * 选传参数:无
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    lists：分类列表及内容
     *
     */
    public function categoryArticle()
    {

        $article_cate = (new \zzcms\home\model\ArticleCategory())->getList(['order' => 'listorder asc', 'where' => ['module' => 'article', 'id' => ['gt', 1], 'status' => 1]]);
        //重新整理分类，以便把对应的文章列表放在分类下面
        $lists = [];
        foreach ($article_cate as $item) {
            $lists[$item['id']] = $item;
        }
        $model = new \zzcms\home\model\Article();
        //文章列表
        $article_lists = $model->getList(['order' => 'listorder desc', 'limit' => 'all', 'field' => 'id,cateid,title,url']);
        foreach ($article_lists as $k => $item) {
            $lists[$item['cateid']]['articles'][] = $item;
        }
        $data = [
            'lists' => $lists
        ];
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }

    /**
     * 分类列表
     * url:http://www.xmyeditor.com/apimobile/help/categorys.html
     * 必传参数: 无
     * 选传参数:无
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    lists：分类列表
     *
     */
    public function categorys()
    {
        $article_cate = getCache('article_category');
        $articles = [];
        foreach ($article_cate as $k => $item) {
            if ($item['module'] == 'article' && $item['status'] == 1) {
                $articles[] = $item;
            }
        }
        $listorder = array_column($articles, 'listorder');
        array_multisort($listorder, SORT_ASC, $articles);
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $articles]);
    }


    /**
     * 分类列表
     */
    public function newlists()
    {
        $article_cate = getCache('article_category');
        $articles = [];
        foreach ($article_cate as $k => $item) {
            if ($item['module'] == 'article' && $item['status'] == 1) {
                $articles[] = $item;
            }
        }
        $listorder = array_column($articles, 'listorder');
        array_multisort($listorder, SORT_ASC, $articles);
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $articles]);
    }


    /**
     * 热门关键词
     * url:http://www.xmyeditor.com/apimobile/help/hotKeywords.html
     * 必传参数:无
     * 选传参数:无
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    hotkeywords：关键词数组
     *
     */
    public function hotKeywords()
    {
        //引入迅搜,搜索入热词需要用到
        include EXTEND_PATH . 'xunsearch/lib/XS.php';
        $xs = new \XS('article');
        $search = $xs->search;
        //关键字
        $keyword_list = $search->getHotQuery();
        $hot_keywords = [];
        foreach ($keyword_list as $key => $item) {
            $hot_keywords[] = $key;
        }
        $data = [
            'hotkeywords' => $hot_keywords,
        ];
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }


    /**
     * 热门问题
     * url:http://www.xmyeditor.com/apimobile/help/hotQuestions.html
     * 必传参数:无
     * 选传参数:无
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    lists：热门问题列表
     *
     */
    public function hotQuestions()
    {
        $model = new \zzcms\home\model\Article();
        $lists = $model->getList(['order' => 'hits desc', 'limit' => 10, 'where' => ['content' => ['neq', ''], 'id' => ['neq', 55], 'status' => 1], 'field' => 'id,title,cateid']);
        $data = [
            'lists ' => $lists,
        ];
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }


    /**
     * 新手上路,进阶技巧
     * url:http://www.xmyeditor.com/apimobile/help/novice.html
     * 必传参数:
     * 选传参数:type：1（新手上路 默认） 2（进阶技巧）
     * 返回值
     *   code：返回状态
     *   msg：提示信息
     *   data：返回信息    lists：文章分类及下属列表
     *
     */
    public function novice()
    {
        $type = isset($this->info['type']) ? intval($this->info['type']) : 1;
        $parentid = $type == 2 ? 17 : 16;
        //新手上路是在分类17下的
        $catelist = (new \zzcms\home\model\ArticleCategory())->getList(['order' => 'listorder DESC', 'where' => ['module' => 'help', 'status' => 1, 'parentid' => $parentid], 'field' => 'catename,id', 'limit' => 'all']);
        if (empty($catelist)) {
            $this->array2json(['code' => 1, 'msg' => '暂无分类数据']);
        }
        $cateids = array_column($catelist, 'id');
        $sub_model = new \zzcms\home\model\ArticleSubtitle();
        //重新整理分类，以便把对应的文章列表放在分类下面
        $lists = [];
        foreach ($catelist as $item) {
            $lists[$item['id']] = $item;
        }
        $article_lists = $sub_model->getList(['order' => 'listorder desc,id desc', 'limit' => 'all', 'where' => ['cateid' => ['in', $cateids], 'status' => 1], 'field' => 'id,title,cateid,articleid']);
        if (empty($article_lists)) {
            $this->array2json(['code' => 1, 'msg' => '暂无文章数据']);
        }
        foreach ($article_lists as $k => $item) {
            if (isset($lists[$item['cateid']]['articles']) && count($lists[$item['cateid']]['articles']) > 9) {
                continue;
            }
            $lists[$item['cateid']]['articles'][] = $item;
        }
        $data = [
            'lists ' => $lists,
        ];
        $this->array2json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }

    /**
     * 分词
     * @param $title
     * @param null $num
     * @return array|string
     */
    private function getTags($title, $num = null)
    {
        $pscws = new \zzcms\util\pscws\Pscws4();
        $path = EXTEND_PATH . 'zzcms/util/pscws/';
        $pscws->set_dict($path . 'dict.utf8.xdb');
        $pscws->set_rule($path . 'etc/rules.utf8.ini');
        $pscws->set_ignore(true);
        $pscws->send_text($title);
        $words = $pscws->get_tops($num);
        $pscws->close();
        $tags = [];
        foreach ($words as $val) {
            $tags[] = $val['word'];
        }
        return implode(',', $tags);
    }


}